package com.isczy.eduservice.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isczy.eduservice.entity.EduCourse;
import com.isczy.eduservice.entity.EduCourseDescription;
import com.isczy.eduservice.entity.EduVideo;
import com.isczy.eduservice.entity.frontvo.CourseFrontVo;
import com.isczy.eduservice.entity.frontvo.CourseWebVo;
import com.isczy.eduservice.entity.vo.CourseInfoVo;
import com.isczy.eduservice.entity.vo.CoursePublishVo;
import com.isczy.eduservice.mapper.EduChapterMapper;
import com.isczy.eduservice.mapper.EduCourseDescriptionMapper;
import com.isczy.eduservice.mapper.EduCourseMapper;
import com.isczy.eduservice.mapper.EduVideoMapper;
import com.isczy.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isczy.servicebase.exceptionHandler.MyException;
import com.isczy.utils.DataResult;
import com.isczy.utils.ResultCode;
import com.isczy.vodapi.VodFeignService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author CZY
 * @since 2021-01-02
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private EduVideoMapper videoMapper;

    @Autowired
    private EduChapterMapper chapterMapper;

    @Autowired
    private VodFeignService vodFeignService;

    /***
     * ***************************************
     * 功能描述:添加课程基本信息
     * @param courseInfoVo
     * @return
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-02 19:30】
     * @author modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCourseInfo(CourseInfoVo courseInfoVo) {
        //向课程表加基本信息
        //CourseInfoVo对象值copy到eduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        baseMapper.insert(eduCourse);
        //向课程简介添加信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        String id = eduCourse.getId();
        courseDescription.setId(id);
        courseDescriptionMapper.insert(courseDescription);
        return id;
    }

    /***
     * ***************************************
     * 功能描述:根据课程id查询课程基本信息
     * @param courseId
     * @return {@link CourseInfoVo}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-05 14:38】
     * @author modify:
     */
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //1 查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        //2 查询描述表
        EduCourseDescription courseDescription = courseDescriptionMapper.selectById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;
    }

    /***
     * ***************************************
     * 功能描述:修改课程信息
     * @param courseInfoVo
     * @return
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-05 14:53】
     * @author modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        //乐观锁
        eduCourse.setVersion(baseMapper.selectById(courseInfoVo.getId()).getVersion());
        baseMapper.updateById(eduCourse);
        //2 修改描述表
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        courseDescriptionMapper.updateById(description);
    }

    /***
     * ***************************************
     * 功能描述:根据课程id查询课程确认信息
     * @param id
     * @return {@link CoursePublishVo}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-05 14:53】
     * @author modify:
     */
    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }

    /***
     * ***************************************
     * 功能描述:删除课程
     * @param courseId
     * @return
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-06 16:40】
     * @author modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCourse(String courseId) {

        //删除小节中阿里云上的视频的视频
        //查询出所有小节的视频id并封装进list
        List<String> videoSourceIdList = new ArrayList<>();
        QueryWrapper<EduVideo> wrapper = new QueryWrapper();
        wrapper.eq("course_id",courseId);
        videoMapper.selectList(wrapper).forEach(eduVideo -> {
            String videoSourceId = eduVideo.getVideoSourceId();
            if (StrUtil.isNotEmpty(videoSourceId)){
                videoSourceIdList.add(videoSourceId);
            }
        });
        if (ArrayUtil.isNotEmpty(videoSourceIdList)){
            DataResult dataResult = vodFeignService.deleteBatch(videoSourceIdList);
            if(dataResult.getCode() == 50000) {
                throw MyException.builder()
                        .code(ResultCode.ERROR)
                        .className(getClass().getName())
                        .methodName(Thread.currentThread().getStackTrace()[1].getMethodName())
                        .message("删除小节视频失败")
                        .params(videoSourceIdList)
                        .build();
            }
        }
        // 根据课程id删除小节
        videoMapper.deleteVideoByCourseId(courseId);

        // 根据课程id删除章节
        chapterMapper.deleteChapterByCourseId(courseId);

        // 根据课程id删除描述
        courseDescriptionMapper.deleteById(courseId);

        // 根据课程id删除课程本身
        baseMapper.deleteById(courseId);
    }

    /***
     * ***************************************
     * 功能描述:查询热门课程，并放入redis
     * @param
     * @return {@link List< EduCourse>}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-13 16:43】
     * @author modify:
     */
    @Override
    @Cacheable(value = "hot",key = "'course'")
    public List<EduCourse> getHotCourseList() {
        //查询前8条热门课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8");
        return baseMapper.selectList(wrapper);
    }

    /***
     * ***************************************
     * 功能描述:条件查询带分页查询课程
     * @param pageParam
     * @param courseFrontVo
     * @return {@link Map< String, Object>}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-20 14:10】
     * @author modify:
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        //2 根据讲师id查询所讲课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StrUtil.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if(!StrUtil.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StrUtil.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StrUtil.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StrUtil.isEmpty(courseFrontVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam,wrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();//下一页
        boolean hasPrevious = pageParam.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    /***
     * ***************************************
     * 功能描述:根据课程id，编写sql语句查询课程信息
     * @param courseId
     * @return {@link CourseWebVo}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-20 14:12】
     * @author modify:
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }
}
